<script setup>
import { addShoes, pageTableData } from "@/api/shoe.js";
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { shoeDeleteById } from "@/api/shoe.js";
import { updateShoe } from "@/api/shoe.js";
import { ElIcon } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

//----------- 数据定义 ---------------------------
const dialogFormVisible = ref(false) // 新增对话框
const editDialogVisible = ref(false) // 编辑对话框
const labelWidth = ref('80px')
const formTitle = ref(null)
const shoes = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const shoeName = ref(null)
const categoryId = ref(null)
const status1 = ref(null)
const total = ref(0)
const imageUrl = ref(null)

const shoeDTO = ref({
  id: null,
  name: null,
  color: null,
  description: null,
  price: null,
  categoryId: null,
  shoeSize: [],
  status: null,
  image: null
})
const formRef = ref(null) // 用于表单验证
const upSelected = ref({...shoeDTO.value})

//----------- 表单验证规则 ---------------------------
const rules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

//----------- 方法定义 ---------------------------
const clearShoeDTO = () => {
  shoeDTO.value = {
    id: null,
    name: null,
    color: null,
    description: null,
    price: null,
    categoryId: null,
    shoeSize: [],
    status: null,
    image: null
  }
}

const getTableData = () => {
  const query = {
    page: currentPage.value,
    pageSize: pageSize.value,
    name: shoeName.value,
    categoryId: categoryId.value,
    status: status1.value
  }
  pageTableData(query).then(res => {
    shoes.value = res.data.records
    total.value = res.data.total
  })
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const deleteShoe = (row) => {
  ElMessageBox.confirm('确认删除该商品吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 将单个 row.id 包装成数组传给 API
    shoeDeleteById([row.id]).then(() => {
      ElMessage.success('删除成功')
      getTableData() // 刷新表格数据
    }).catch(error => {
      ElMessage.error('删除失败：' + error.message)
    })
  })
}

const handleAdd = () => {
  formTitle.value = '新增商品'
  dialogFormVisible.value = true
}


const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      addShoes(shoeDTO.value)
          .then(res => {
            ElMessage.success('添加成功')
            dialogFormVisible.value = false
            clearShoeDTO()
            getTableData()
          })
          .catch(error => {
            ElMessage.error('添加失败：' + error.message)
          })
    }
  })
}
const updatedShoe = () => {
  updateShoe(upSelected.value).then(res => {
    ElMessage.success('修改成功')
    editDialogVisible.value = false
    getTableData()
  })
}

const handleAvatarSuccess = (response,uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  upSelected.value.image = response.data.url
}

//----------- 选项数据 ---------------------------

const buttons = [
  { value: 1, label: '运动鞋' },
  { value: 2, label: '休闲鞋' },
  { value: 3, label: '篮球鞋' },
  { value: 4, label: '板鞋' }
]
const showEdit = (row) => {
  upSelected.value = JSON.parse(JSON.stringify(row))
  upSelected.value.status = Number(row.status) // 确保是数字类型
  imageUrl.value = row.image
  editDialogVisible.value = true

}

const sizeOptions = [38, 39, 40, 41, 42, 43].map(size => ({
  value: size,
  label: size.toString()
}))

// 初始化加载数据
getTableData()
</script>

<template>
  <div class="container">
    <!-- 顶部标题 -->
    <div id="title">商品管理</div><br>

    <!-- 搜索表单 -->
    <el-form :inline="true" class="search-form">
      <el-form-item label="商品名称：">
        <el-input
            v-model="shoeName"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="getTableData"
        />
      </el-form-item>

      <el-form-item label="商品类别：" style="width: 300px">
        <el-select
            v-model="categoryId"
            placeholder="请选择类别"
            clearable
        >
          <el-option
              v-for="item in buttons"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getTableData">查询</el-button>
        <el-button @click="shoeName = null; categoryId = null">清空</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->

    <el-button type="success" @click="handleAdd">+ 新增商品</el-button>

    <!-- 商品表格 -->
    <el-table :data="shoes" border style="width: 100%" class="mt-20" >
      <el-table-column prop="image" label="商品图片" width="120">
        <template #default="{row}">
          <el-image :src="row.image" style="width: 80px; height: 80px" fit="contain" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="120" />
      <el-table-column prop="color" label="颜色" width="100" />
      <el-table-column prop="price" label="价格" width="100">
        <template #default="{row}">
          ¥{{ row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column prop="updateTime" label="更新时间" width="160" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="category" label="分类" width="120">
        <template #default="{row}">
          {{ buttons.find(b => b.value === row.categoryId)?.label }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="是否销售" width="100">
        <template #default="{row}">
          <el-tag :type="row.status ? 'success' : 'danger'">
            {{ row.status ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{row}">
          <el-button size="small" @click="showEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteShoe(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :background = true
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 新增商品对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="formTitle" width="600px">
      <el-form ref="formRef" :model="shoeDTO" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="shoeDTO.name" />
        </el-form-item>
        <el-form-item label="颜色">
          <el-input v-model="shoeDTO.color" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="shoeDTO.price" type="number">
            <template #append>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="shoeDTO.categoryId" style="width: 100%">
            <el-option
                v-for="item in buttons"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="shoeDTO.description" type="textarea" />
        </el-form-item>
        <el-form-item label="尺码">
          <el-select v-model="shoeDTO.shoeSize" multiple style="width: 100%">
            <el-option
                v-for="item in sizeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否销售" prop="status">
          <el-switch
              v-model="shoeDTO.status"
              :active-value="1"
              :inactive-value="0"
              active-text="销售中"
              inactive-text="已下架"
              active-color="#13ce66"
              inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              action="/api/file/upload"
              :show-file-list="false"
              :on-success="(res) => shoeDTO.image = res.data.url"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                {{ shoeDTO.image || '未上传图片' }}
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false; clearShoeDTO()">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 编辑商品对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑商品" width="600px">
      <el-form :model="upSelected" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="upSelected.name" />
        </el-form-item>
        <el-form-item label="颜色">
          <el-input v-model="upSelected.color" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="upSelected.price" type="number">
            <template #append>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="upSelected.categoryId" style="width: 100%">
            <el-option
                v-for="item in buttons"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="upSelected.description" type="textarea" />
        </el-form-item>
        <el-form-item label="是否销售" prop="status">
          <el-switch
              v-model="upSelected.status"
              :active-value="1"
              :inactive-value="0"
              active-text="销售中"
              inactive-text="已下架"
              active-color="#13ce66"
              inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              class="avatar-uploader"
              action="/api/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updatedShoe">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.page-container {
  padding: 24px;
  background-color: #fff;
  min-height: calc(100vh - 64px);
  box-sizing: border-box;
}

#title {
  margin-bottom: 16px;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  border-left: 4px solid #409eff;
  padding-left: 8px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.search-form .el-form-item {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}

.search-form .el-input,
.search-form .el-select {
  width: 200px;
}

.mt-20 {
  margin-top: 20px;
}

.el-table {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  overflow: hidden;

  th, td {
    padding: 12px 0;
  }

  tr:hover {
    background-color: #f8f9fd;
  }

  /* 空状态优化 */
  .el-table__empty-text {
    color: #999;
  }
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;

  &:hover {
    border-color: var(--el-color-primary);
  }
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: contain;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.el-pagination {
  margin-top: 20px;
}

.el-button {
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.el-button--success {
  &:hover {
    background-color: #67c23a;
    border-color: #67c23a;
  }
}
</style>